import axios from "axios";
import cache from "./local_cache"
import eventLoop from "./event_loop"
import cst from "./cst"

class Ajax{
    constructor(){
        this.host = process.env.VUE_APP_HOST;
    }

    setUser(user){
        this.user = user;
    }
    /**
     *  get请求
     *  @param  url     请求的地址
     *  @param  data    请求的数据
     *  @param  eventName   请求成功或者失败后 发送事件的事件名字
     *  使用解耦的方式，避开组件在声明周期之外可以监听到这里的结果
     */
    get(url,data,eventName){

    }

    getWithToken(url,data,eventName){
        let that = this;
        if(this.user == null || this.user.token == null){
            eventLoop.publishEvent({
                type:eventName,
                code:-3,
                msg:"用户未登录",
                data:{}
            })
            return ;
        }
        axios.request({
            url:url,
            method:"get",
            data:data,
            //  添加token参数
            headers:{
                'Authorization': 'Bearer ' + this.user.token
            }
        })
            .then(result => {

            })
            .catch(e => {

            })
    }

    post(url,data,eventName){
        console.log(this.host)
        axios.request({
            url:this.host+url,
            method:"POST",
            data:data
        })
            .then(result => {
                eventLoop.publishEvent({
                    type:eventName,
                    status:'success',
                    data:result
                })
            })
            .catch(e => {
                eventLoop.publishEvent({
                    type:eventName,
                    status:"error",
                    data:e
                })
            })
    }

    postWithToken(url,data,eventName){

    }
}

let ajax = new Ajax();

export default ajax;